
export default {
  namespaced: true,
  state: {
    // 购物车列表
    cartList: []
  },
  getters: {
  },
  actions: {
    /**
     * 加入购物车
     * @param state
     * @param commit
     * @param goods
     * @returns {Promise<any>}
     */
    addCart ({ state, commit }, goods) {
      return new Promise(async resolve => {
        state.cartList.push(goods)
        commit('add', goods.goodsId)
        await Megalo.setStorage({ key: 'cartList', data: state.cartList })
        // end
        resolve()
      })
    },
    /**
     * 从持久化数据读取购物车列表
     * @param state
     * @param dispatch
     * @returns {Promise<any>}
     */
    load ({ state, dispatch }) {
      return new Promise(async resolve => {
        let res = await Megalo.getStorage({ key: 'cartList' })
        state.cartList = res.data
        // end
        resolve()
      })
    }
  },
  mutations: {
    // 添加产品数量
    async addition (state, goodsId) {
      let _stop = false
      for (let value of state.cartList) {
        if (value.goodsId === goodsId) {
          value.goodsSum = value.goodsSum + 1
          await Megalo.setStorage({ key: 'cartList', data: state.cartList })
          _stop = true
        }
        if (_stop) {
          return false
        }
      }
    },
    // 减小产品数量
    async subtraction  (state, goodsId) {
      let _stop = false
      for (let value of state.cartList) {
        if (value.goodsId === goodsId) {
          value.goodsSum = value.goodsSum - 1
          await Megalo.setStorage({ key: 'cartList', data: state.cartList })
          _stop = true
        }
        if (_stop) {
          return false
        }
      }
    }
  }
}
